<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class UserController extends BaseController
{
    /**
     * 登录接口 username  password
     */
    public function login(Request $request) {
        try{
            $username = $request->input('username', '');
            if (empty($username)) return $this->response(400, '请填写用户名');
            $password = $request->input('password', '');
            if (empty($password)) return $this->response(400, '请填写密码');
            // select * from users where username = ''
            // $user是一个对象（记录，字段是该对象对应的属性）
            $user = User::select(['id', 'username', 'password'])->where('username', $username)->first();
            if (empty($user)) return $this->response(400, '用户名不存在');
            if ($user->password != md5($password)) return $this->response(400, '密码不正确');
            return $this->response(200, '登录成功', $user);
        }catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }
    }

    /**
     * 授权登录
     */
    public function auth(Request $request) {
        try{
            $code = $request->input('code', '');
            if (empty($code)) return $this->response(400, 'code参数错误');
            $config = config('wechat.mini');
            $app = Factory::miniProgram($config);
            $result = $app->auth->session($code);
            if (!isset($result['openid'])) return $this->response(400, '获取用户openid失败');
            $user = User::where('openid', $result['openid'])->first();
            // $is_perfect = 0  未完善   1 已完善
            $is_perfect = 1;
            if (empty($user)) {
                $data = [
                    'openid' => $result['openid'],
                    'username' => '',
                    'password' => ''
                ];
                if (!User::create($data)) {
                 return $this->response(400, '用户授权登录失败');
                }
                $is_perfect = 0;
            } else {
                if (empty($user->username) || empty($user->password)) $is_perfect = 0;
            }
            return $this->response(200, '登录成功', ['openid' => $result['openid'], 'is_perfect' => $is_perfect]);
        }catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }
    }
}
